package com.moyun.zbmy.zizhou.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoBean;
import com.moyun.zbmy.zizhou.beans.SubscriptionNoTypeBean;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.SubscriptionNoAdapter;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;
import com.ruihang.generalibrary.utils.ListUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 搜索订阅号
 */
public class SearchSubscriptionNoActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , SubscriptionNoAdapter.OnSubscriptionNoClickListener {

    @BindView(R.id.input_key)
    protected EditText searchKey;
    @BindView(R.id.search_result_layout)
    protected LinearLayout searchResultLayout;
    @BindView(R.id.search_null_layout)
    protected RelativeLayout searchNullLayout;
    @BindView(R.id.refresh_layout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;

    public static final String INPUT_KEY = "input_key";
    private String inputKey;
    private SubscriptionNoAdapter adapter;
    private int mPageNo = 1;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private List<SubscriptionNoBean> dataList = new ArrayList<>();

//    搜索接口
//    http://118.122.74.146:7083/keywordSearchWx?siteNumber=405
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inputKey = getIntent().getStringExtra(INPUT_KEY);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_subscription_no_search);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView() {
        searchKey.setText(inputKey);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setLoadMoreEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        //设置RecycleView显示的方向是水平还是垂直 GridLayout.HORIZONTAL水平  GridLayout.VERTICAL默认垂直
        gridLayoutManager.setOrientation(GridLayout.VERTICAL);
        //设置布局管理器， 参数gridLayoutManager对象
        mRecyclerView.setLayoutManager(gridLayoutManager);
//        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRefreshLayout.autoRefresh();
        searchKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = searchKey.getText().toString().trim();
//                if (TextUtils.isEmpty(str)) {
//                    cleanBtn.setVisibility(View.GONE);
//                } else {
//                    cleanBtn.setVisibility(View.VISIBLE);
//                }
            }
        });
    }

    @Override
    public void onLoadMore() {
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        dataList.clear();
        mPageNo = 1;
        mIsLoading = true;
        searchData();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            inputKey = searchKey.getText().toString().trim();
            if (TextUtils.isEmpty(inputKey)) {
                toast("请输入关键词");
            } else {
                //TODO  搜索
                mRefreshLayout.autoRefresh();
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 搜索订阅号
     */
    private void searchData() {

        NetUtils.getNetAdapter().searchSubscriptionNoList(getOwnerName(), inputKey, new AbsListNetCallback<SubscriptionNoBean>(ListTypeUtils.SubscriptionNoBean(),0) {
            @Override
            public void onSuc(List<SubscriptionNoBean> list) {
                if (ListUtils.isListValued(list)) {
                    dataList.addAll(list);
                    initData();
                    searchResultLayout.setVisibility(View.VISIBLE);
                    searchNullLayout.setVisibility(View.GONE);
                } else {
                    searchResultLayout.setVisibility(View.GONE);
                    searchNullLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);

                if (mPageNo > 1) {
                    mPageNo--;
                }
            }

            @Override
            public void onEnd() {
                onNetFinish();
                mIsLoading = false;
                onNetFinish();
            }
        });
    }


    private void initData() {
        if (null == adapter) {
            adapter = new SubscriptionNoAdapter(this, dataList, this);
            mRecyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            adapter.setData(dataList);
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(false );

    }

    @Override
    public void OnSubscriptionNoClick(SubscriptionNoBean bean) {
        //TODO 点击公众号
        Intent intent = new Intent(this, SubscriptionNoDetailActivity.class);
        intent.putExtra(SubscriptionNoDetailActivity.SUBSCRIPTION_NO_ID, bean.getWxId());
        intent.putExtra(BaseActivity.EX_TITLE, bean.getWxName());
        startActivity(intent);
    }


    @OnClick(value = {R.id.cancel})
    public void OnClick(View view) {
        switch (view.getId()) {

            case R.id.cancel:
                onBackPressed();
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                mRefreshLayout.autoRefresh();
                setResult(RESULT_OK);
            }
        }
    }



}
